package br.com.mundoj.subscription.client;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FormattedString {
	public final String plain, formatted;
	private final List<Integer> separatorIndexes;
	private final List<Character> separators;
	private final int plainSize;
	
	public FormattedString(String format, String str) {
		ArrayList<Character> chars = new ArrayList();
		ArrayList<Integer> indexes = new ArrayList();
		for (int i=0; i<format.length(); i++) {
			char c = format.charAt(i);
			if (c!='_') {
				chars.add(c);
				indexes.add(i);
			}
		}
		separators = Collections.unmodifiableList(chars);
		separatorIndexes = Collections.unmodifiableList(indexes);
		plainSize = format.length() - separatorIndexes.size();
		
		plain = formatPlain(str);
		formatted = formatPlaceHolders();
	}
	
	private String formatPlain(String str) {
		if (str==null)
			str = "";
		else {
			str = str.replaceAll("[^0-9]", "");
			if (str.length()>plainSize)
				str = str.substring(0, plainSize);
		}
		return str;
	}

	private String formatPlaceHolders() {
		String res = plain;
		int size = res.length();
		for (int i = size; i<plainSize; i++)
			res = res.concat("_");
		
		for (int i=0; i<separators.size(); i++) {
			int index = separatorIndexes.get(i);
			String s = String.valueOf(separators.get(i));
			res = res.substring(0, index).concat(s).concat(res.substring(index));
		}
		return res;
	}
	
	public boolean isValid() {
		return plain.length()==plainSize;
	}

	public int nextCursorPosition(int pos) {
		int size = plain.length();
		for (int i=0; i<separatorIndexes.size(); i++) {
			int index = separatorIndexes.get(i) + 1;
			if (pos==index) {
				if (size==(index-i))
					pos++;
				else if (size==(index-i-1)) 
					pos--;
				break;
			}
			if (index>pos)
				break;
		}
		return pos;
	}
}